package MyCollectiones;

import java.util.*;

/**
 * @Auther: MFM
 * @Date: 2021/7/30 - 07 - 30 - 14:55
 * @version: 1.0
 */

public class MyToolCollection {
    public void reverse(List<String> list) {
        for (int i = 0; i < list.size() / 2; i++) {
            String o = list.get(i);
            list.set(i, list.get(list.size() - i - 1));
            list.set(list.size() - i - 1, o);
        }
    }

    public static <T> void sort(List<T> list) {
        for (int i = 0; i < list.size(); i++) {
            for (int j = i + 1; j < list.size(); j++) {
                T comp1 = list.get(i);
                Comparable<T> t1 = (Comparable<T>) comp1;
                T comp2 = list.get(j);
                if (t1.compareTo(comp2) > 0) {
                    list.set(i, list.get(j));
                    list.set(j, comp1);
                }
            }
        }
    }

    public static <T> void sort(List<T> list, Comparator<T> comparator) {
        for (int i = 0; i < list.size(); i++) {
            for (int j = i + 1; j < list.size(); j++) {
                T t1 = list.get(i);
                T t2 = list.get(j);
                if (comparator.compare(t1, t2) == 1) {
                    list.set(i, t2);
                    list.set(j, t1);
                }
            }
        }
    }

    public static <T> void rotate(List<T> list, int distance) {
        int i = distance % list.size();
        Queue<T> queue = new LinkedList<>();
        if (i > 0) {

            for (int j = 0; j < Math.abs(i); j++) {
                queue.add(list.remove(list.size() - 1));
            }
            while (queue.size() > 0) {
                list.add(0, queue.poll());
            }

        } else if (i < 0) {
            for (int j = 0; j < Math.abs(i); j++) {
                queue.add(list.remove(0));
            }
            while (queue.size() > 0) {
                list.add(queue.poll());
            }
        }
    }

    public static <T> int binarySearch(List<T> list, T key) {
        int start = 0, end = list.size() - 1;
        while (end - start >= 0) {
            int mid = (start + end) / 2;
            T value = list.get(mid);
            Comparable<T> comp = (Comparable<T>) value;
            if (comp.compareTo(key) == 0) {
                return mid;
            } else if (comp.compareTo(key) == 1) {
                end = mid;
            } else {
                start = mid + 1;
            }
        }


        return -1;
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(11);
        list.add(5);
        list.add(6);
        list.add(13);
        list.add(17);
        sort(list);
        System.out.println(binarySearch(list, 11));
    }
}
